package com.example.order.receiver;

import com.example.common.util.constant.CommonUtilConstants;
import com.example.common.util.utils.StringUtils;
import com.example.order.service.OrderInfoService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author juzipi
 * @Date 2021/7/29 19:38
 * @Info
 */
@Component
public class OrderInfoReceiver {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private OrderInfoService orderInfoService;


    //!! 注意这里监听的是 task队列！！
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = CommonUtilConstants.TASK_QUEUE),
            exchange = @Exchange(value = CommonUtilConstants.TASK_EXCHANGE),
            key = {CommonUtilConstants.TASK_ROUTING}
    ))
    public void taskConsumer(Boolean aBoolean, Channel channel, Message message) throws IOException {
        try {
            //消费掉消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
            logger.info("消息已确认 -------------> "+aBoolean);
            if (aBoolean){
                orderInfoService.remindPatient();
            }
        } catch (IOException e) {
            e.printStackTrace();
            //消费失败,此条消息重新回到队列
            logger.error("消息未成功消费,返回消息队列 -------------> "+e.getMessage());
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
        }
    }


}
